<template>
	<view class="upload-content">
		<scroll-view
		  scroll-y="true"
		  @scrolltolower="loadMore"
		  :scrolltolower-enabled="true"
		  :refresher-triggered="triggered"
		  class="scroll-view-class"
		>
		
		<!--  @refresherrefresh="refresherrefresh"
		  @scrolltoupper="refresherrefresh" -->
		  <view style="display: flex;justify-content: space-between;">
			  <view class="upload-add-btn" v-if="rduLength > 0" @click="chooseImage"></view>
		  	<view style="text-align: right;font-size: 38upx;">
				<view style="margin-bottom: 10px;">
						参考号：{{bizKey}}
				</view>
				<view >
					共 <text style="color: red;font-size: 48upx;">{{list.length}}</text> 张
				</view>
		  	</view>
		  </view>
		
		
		<view v-for="(item, index) in imageList" :key="index">
			<view class="upload-item">
				<image class="upload-img" :src="item.filePath" mode="aspectFill" @click="previewImage(index)"></image>
				<image class="upload-del-btn" @click="delImage(item,index)" src=""
				 mode="scaleToFill">
				</image>
				<view class="upload-progress" v-if="item.progress < 100">{{item.progress}}%</view>
				<view class="">
					{{item.createByName}}
				</view>
				<view class="">
					{{item.createDate}}
				</view>
			</view>
		</view>
		</scroll-view>
	</view>
</template>

<script>
	import SparkMD5 from '@/components/spark-md5/spark-md5.js'
	import {
		mapState
	} from 'vuex';
	export default {
		components: {
			SparkMD5
		},
		data() {
			return {
				query: {
				  pageNo: 1,
				  pageSize: 10,
				},
				triggered: false,
				loadStatus: "loadmore",
				// imageList: this.imgArray,
				imageList: [],
				imageIdlist:this.imageIdslist,
				getMd5Checked:'',
				delImageIds :[],
				list:this.imgArray
			};
		},
		props: {
			url: {
				type: String,
				value: '' //上传接口地址
			},
			imageIdslist:{
				type: Array,
				value:[]
			},
			imgArray:{
				type: Array,
				value:[]
			},
			count: {
				type: Number,
				value: 4 //单次可选择的图片数量
			},
			length: {
				type: Number,
				value: 9999 //可上传总数量
			},
			bizKey: {
				type: String,
				value: '' //文件类型
			},
			bizType: {
				type: String,
				value: ''
			},
			uploadType: {
				type: String,
				value: 'image' //上传类型
			},
			imageMaxWidth: {
				type: Number,
				value: -1 //最大宽度
			},
			imageMaxHeight: {
				type: Number,
				value: -1 //最大高度
			},
			fileMd5: {
				type: String,
				value: '' //文件MD5加密
			},
			fileUploadId: {
				type: String,
				value: 'image' //上传文件ID
			},
			type: {
				type: String,
				value: '' //上传类型
			},
		},
		computed: {
			rduLength() {
				
				this.imageList = this.list.slice(0,this.query.pageSize)
				// return this.length - this.imageList.length;
				return this.length - this.list.length;
				
			},
			...mapState(['hasLogin', 'userInfo', 'auditlist'])
		},
		methods: {
			loadMore() {
			  this.loadStatus = "loading";
			  console.log(this.loadStatus,'this.loadStatus')
			  setTimeout(() => {
			    this.query.pageSize += 10
				this.imageList = this.list.slice(0,this.query.pageSize)
				console.log(this.query.pageSize,'pageSize=====');
				if(this.query.pageSize > this.list.length){
					this.loadStatus = "nomore";
				}
			  }, 100);
			},
			//选择图片
			chooseImage: function() {
				uni.chooseImage({
					count: this.rduLength < this.count ? this.rduLength : this.count, //最多可以选择的图片张数，默认9
					sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
					success: (res) =>{
						const images = res.tempFilePaths;
						const imagefiles = res.tempFiles;
						console.log(res,'res=====');
						this.uploadFiles(images, imagefiles);
					}
				});
			},
			//上传图片
			async uploadFiles(images, imagefiles) {
				this.imageList.unshift({
					filePath: images[0],
					file: imagefiles[0],
					progress: 0
				});
				this.list.unshift({
					filePath: images[0],
					file: imagefiles[0],
					progress: 0
				});
				uni.showLoading({
					title: '正在上传...',
					mask: true,
				})
				try {
					//this.handlePrepareUpload(imagefiles[0]);
					this.timer = setTimeout( async()=>{   //设置延迟执行
					   let uploadUrl = await this.uploadImage(images[0], imagefiles[0]);
					   if (uploadUrl !== false) {
					   	images.splice(0, 1);
					   	// this.imageList[this.imageList.length - 1].src = uploadUrl;
					   	this.imageList[0].src = uploadUrl;
					   	this.list[0].src = uploadUrl;
					   	//判断是否需要继续上传
					   	if (images.length > 0 && this.rduLength > 0) {
					   		this.uploadFiles(images);
					   	} else {
					   		uni.hideLoading();
					   	}
					   } else {
					   	//上传失败处理
					   	// this.imageList.pop();
					   	this.imageList.shift();
					   	this.list.shift();
						
					   	uni.hideLoading();
					   	uni.showToast({
					   		title: '上传中出现问题，已终止上传',
					   		icon: 'none',
					   		mask: true,
					   		duration: 2000
					   	});
					   }
					},1000)
				} catch (err) {
					console.log(err);
					uni.hideLoading();
					return;
				}
			},
			uploadImage: function(file, imagefile) {
				let that = this
				let size = '';
				var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
				  for (var i = 0; i < 4; i++) {
					  //设置随机数范围,这设置为0 ~ 36
					  var index = Math.floor(Math.random() * 9);
					  //字符串拼接 将每次随机的字符 进行拼接
					  size += random[index];
				  }
				let DateTime = new Date().getTime();
				let fileEntityId = DateTime +''+ size;
				this.imageIdlist.unshift(fileEntityId);
				return new Promise((resolve, reject) => {
					//发送给后端的附加参数
					const formData = {
						thumb_mode: 1,
						__sid: this.userInfo.sessionid,
						bizKey: this.bizKey,
						bizType: this.bizType,
						uploadType: 'image',
						imageMaxWidth: 700,
						imageMaxHeight: 1024,
						chunkSize: 10485760,
						fileMd5: '',
						fileName: imagefile.name,
						fileUploadId: fileEntityId,
						fileEntityId: fileEntityId,
						name: imagefile.name,
						type: imagefile.type
					};
					let params = '';
					for (let k in formData) {
						if (params) params += '&';
						params += `${k}=${formData[k]}`;
					}
					console.log(111112222222);
					this.uploadTask = 
					uni.uploadFile({
						url: this.url + '?'+params,
						filePath: file,
						name: 'file',
						// header:{
						// 	"Access-Control-Allow-Origin":'*'
						// },
						// formData: formData,
						success(uploadFileResult) {
							const uploadFileRes = JSON.parse(uploadFileResult.data) || {};
							if (uploadFileRes.result == 'true') {
								// that.imageList[that.imageList.length - 1].createByName = uploadFileRes.fileUpload.createByName
								// that.imageList[that.imageList.length - 1].createDate = uploadFileRes.fileUpload.createDate
								// that.imageList[that.imageList.length - 1].id = uploadFileRes.fileUpload.id
								that.imageList[0].createByName = uploadFileRes.fileUpload.createByName
								that.imageList[0].createDate = uploadFileRes.fileUpload.createDate
								that.imageList[0].id = uploadFileRes.fileUpload.id
								
								that.list[0].createByName = uploadFileRes.fileUpload.createByName
								that.list[0].createDate = uploadFileRes.fileUpload.createDate
								that.list[0].id = uploadFileRes.fileUpload.id
								
								that.$forceUpdate()
								console.log(uploadFileRes,'uploadFileRes==');
								resolve(uploadFileRes.data);
							} else {
								reject(uploadFileRes);
								reject('接口返回错误');
							}
							uni.hideLoading();
						},
						fail(e) {
							console.log(e,55555555);
							reject('网络链接错误');
							uni.hideLoading();
						}
					});
					
					// uni.request({
					// 	url:this.url,
					// 	data:formData,
					// 	header: {
					// 		'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
					// 	},
					// 	method: 'POST',
					// 	success:function(data){
					// 		let res = data.data
					// 		if (res.result == 'true') {
					// 			resolve(res.data);
					// 		} else {
					// 			reject(res);
					// 			reject('接口返回错误');
					// 		}
					// 		uni.hideLoading();
					// 	}.bind(this),
					// 	fail:function(){
					// 			reject('网络链接错误');
					// 			uni.hideLoading();
					// 	}.bind(this),
					// });
					//上传进度
					this.uploadTask.onProgressUpdate((progressRes) => {
						// this.imageList[this.imageList.length - 1].progress = progressRes.progress;
						this.imageList[0].progress = progressRes.progress;
						this.list[0].progress = progressRes.progress;
						
					});
				});
			},
			//删除图片
			delImage: function(item,index) {
				console.log(item);
				uni.showModal({
					content: '确定要删除这张图片么？',
					success: (confirmRes) => {
						// this.delImageIds.push(this.imageIdlist[index]);
						if (confirmRes.confirm) {
							
							uni.request({
								url:this.serverURL_a+'/so/app/fileuplaod/delFile',
								data:{
									bizKey:this.bizKey,
									delId : item.id,
									__sid:this.userInfo.sessionid
								},
								header: {
									'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
								},
								method: 'POST',
								success:function(data){
									if(data.data.result == "true"){
										this.imageList.splice(index, 1);
										this.list.splice(index, 1);
										
										this.imageIdlist.splice(index, 1);
									}
									this.$api.msg(data.data.message);
								}.bind(this),
								fail:function(){
									this.$api.msg('服务已停止,请稍后再试');
									return;
								}.bind(this),
							});
							
						}
					}
				});
			},
			//预览图片
			previewImage: function(index) {
				const urls = [];
				this.imageList.forEach((item) => {
					urls.push(item.filePath);
				})
				uni.previewImage({
					current: urls[index],
					urls: urls,
					indicator: "number"
				})
			},
			getImageId(){
				return this.imageIdlist;
			},
			getdelImageIds(){
				return this.delImageIds;
			}
		}
	}
</script>

<style lang="scss">
	.scroll-view-class{
		height: calc(100vh - 50px)
	}
	.upload-content {
		padding: 24upx 0 0 0;
		background-color: #fff;
		overflow: hidden;
	}

	.upload-item {
		padding: 10upx;
		position: relative;
		float: left;
		width: 48%;
		height: 360upx;
		margin-right: 10upx;
		margin-bottom: 30upx;
		border: 2px solid #aaa;

		// &:nth-child(4n) {
		// 	margin-right: 0;
		// }

		.upload-img {
			// width: 150upx;
			width: 100%;
			height: 70%;
			// height: 200upx;
			border-radius: 8upx;
		}

		.upload-del-btn {
			position: absolute;
			right: -16upx;
			// left: 135upx;
			top: -14upx;
			width: 36upx;
			height: 36upx;
			border: 4upx solid #fff;
			border-radius: 100px;
		}

		.upload-progress {
			position: absolute;
			left: 0;
			top: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, .4);
			color: #fff;
			font-size: 24upx;
			border-radius: 8upx;
		}
	}

	.upload-add-btn {
		position: relative;
		margin-bottom: 20upx;
		// float: left;
		width: 150upx;
		height: 150upx;
		z-index: 99;
		border-radius: 8upx;
		background: #f9f9f9;

		&:before,
		&:after {
			content: " ";
			position: absolute;
			top: 50%;
			left: 50%;
			-webkit-transform: translate(-50%, -50%);
			transform: translate(-50%, -50%);
			width: 4upx;
			height: 60upx;
			background-color: #d6d6d6;
		}

		&:after {
			width: 60upx;
			height: 4upx;
		}

		&:active {
			background-color: #f7f7f7;
		}
	}
</style>
